#!/bin/bash
# Casdoor 配置脚本

echo "🔧 Casdoor 配置向导"
echo "==================="

# 获取局域网IP
get_lan_ip() {
    if command -v ip &> /dev/null; then
        ip route get 1 | awk '{print $7; exit}'
    elif command -v ifconfig &> /dev/null; then
        ifconfig | grep -E "inet.*broadcast" | awk '{print $2}' | head -1
    else
        echo "192.168.1.100"  # 默认值
    fi
}

LAN_IP=$(get_lan_ip)
echo "🌐 检测到的局域网IP: $LAN_IP"
read -p "确认使用此IP吗? (直接回车确认，或输入正确IP): " input_ip
if [ ! -z "$input_ip" ]; then
    LAN_IP=$input_ip
fi

echo ""
echo "第一步：启动 Casdoor 服务"
echo "========================"

# 启动 Casdoor
echo "🚀 启动 MySQL 和 Casdoor..."
docker-compose -f docker-compose.casdoor-only.yml up -d

echo "⏳ 等待服务启动（需要约 2-3 分钟）..."
echo "正在检查 Casdoor 健康状态..."

# 等待 Casdoor 启动
max_attempts=60
attempt=0
while [ $attempt -lt $max_attempts ]; do
    if curl -s -f http://localhost:8000/api/get-account > /dev/null 2>&1; then
        echo "✅ Casdoor 服务已启动！"
        break
    fi
    
    echo -n "."
    sleep 5
    attempt=$((attempt + 1))
done

if [ $attempt -eq $max_attempts ]; then
    echo "❌ Casdoor 启动超时，请检查日志: docker-compose logs casdoor"
    exit 1
fi

echo ""
echo "第二步：配置 Casdoor 应用"
echo "========================"
echo "🌐 请在浏览器中访问: http://$LAN_IP:8000"
echo ""
echo "📋 默认管理员账号："
echo "   用户名: admin"
echo "   密码: 123"
echo ""
echo "📝 创建应用步骤："
echo "   1. 登录后点击左侧菜单 'Applications'"
echo "   2. 点击 'Add' 按钮创建新应用"
echo "   3. 填写以下信息："
echo "      - Name: todo-app"
echo "      - Display name: TODO List"
echo "      - Organization: built-in"
echo "      - Redirect URLs: http://$LAN_IP:3000/api/auth/callback"
echo "   4. 点击 'Save' 保存"
echo "   5. 记录生成的 'Client ID' 和 'Client secret'"
echo ""

read -p "完成应用配置后，请输入 Client ID: " client_id
read -p "请输入 Client Secret: " client_secret

echo ""
echo "第三步：更新环境变量"
echo "==================="

# 检查并创建 env.docker 文件
if [ ! -f "env.docker" ]; then
    if [ -f "env.docker.example" ]; then
        cp env.docker.example env.docker
    else
        echo "❌ 未找到 env.docker.example 文件"
        exit 1
    fi
fi

# 更新环境变量
echo "📝 更新 env.docker 文件..."
sed -i.bak "s/YOUR_LAN_IP/$LAN_IP/g" env.docker
sed -i.bak "s/your_client_id_here/$client_id/g" env.docker
sed -i.bak "s/your_client_secret_here/$client_secret/g" env.docker

# 为内部容器通信设置 Casdoor 端点
sed -i.bak "s|CASDOOR_ENDPOINT=.*|CASDOOR_ENDPOINT=http://casdoor:8000|g" env.docker

echo ""
echo "第四步：启动 TODO 应用"
echo "====================="

echo "🚀 启动完整服务栈..."
docker-compose --env-file env.docker up -d

echo ""
echo "✅ 部署完成！"
echo "============="
echo "📱 访问地址："
echo "   - TODO 应用: http://$LAN_IP:3000"
echo "   - Casdoor 管理: http://$LAN_IP:8000"
echo ""
echo "🔧 管理命令："
echo "   查看状态: docker-compose ps"
echo "   查看日志: docker-compose logs -f todo-app"
echo "   停止服务: docker-compose down"
echo ""
echo "🎉 现在您可以使用 TODO List 应用了！" 